import { Button, message, Table, Modal } from 'antd'
import axios from 'axios'
import React, { useEffect, useState } from 'react'
import base from '../../routes/baseUrl'
import {
  WarningOutlined
} from '@ant-design/icons'
const { confirm } = Modal

export default function StudentList() {

  const [dataSource, setDataSource] = useState([]) // 学生列表数据
  const { id } = JSON.parse(sessionStorage.getItem('token'))

  const columns = [
    {
      title: '学号',
      dataIndex: 'id',
      render: id => <b>{id}</b>
    },
    {
      title: '姓名',
      dataIndex: 'name'
    },
    {
      title: '操作',
      render: (item) => <Button type='danger' onClick={() => confirmDelete(item)}>退选</Button>
    }
  ]

  useEffect(() => {
    axios.get(base + `/teachers/${id}?_embed=students`).then(res => {
      setDataSource(res.data.students)
    })
  }, [id])

  const confirmDelete = (item) => {
    // console.log(item)
    confirm({
      title: `确定要退选${item.name}同学吗？`,
      icon: <WarningOutlined />,
      content: '注意！该操作不可逆',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        console.log('确认退选')
        axios.patch(base + `/students/${item.id}`, { teacherId: 904 }).then(res => {
          message.success('退选成功')
          setDataSource(dataSource.filter(data => data.id !== item.id))
        })
      },
      onCancel() {
        console.log('操作取消')
      }

    })
  }

  return (
    <div>
      <h2>已选学生列表</h2>
      <Table columns={columns} dataSource={dataSource} rowKey='id' />
    </div>
  )
}
